﻿using System;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;


namespace AnaViewer
{
    partial class OptionsForm : Form
    {
        Properties.Settings settings = Properties.Settings.Default;
        public OptionsForm()
        {
            InitializeComponent();

            foreach (string key in Yandui.Types.Keys)
                cmbYanduiType.Items.Add(key);
            if(cmbYanduiType.Items.Count > 0)
                cmbYanduiType.SelectedIndex = 0;

            FillCmdThemes();

            //初始化默认状态
            btnValidateAna.Enabled = false;//因为 Ana 链接文本框为空，所以为禁用
            btnValidateRss.Enabled = false;
            chkUseBackImage.Checked = true;//因为文本框和浏览按钮的状态是可用的

            chkAutoStart.CheckedChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };

            chkHideMainForm.CheckedChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };

            txtRssFeedUri.TextChanged += delegate(object sender, EventArgs e)
            { this.IsModified = true; btnValidateRss.Enabled = !(txtRssFeedUri.Text == null || txtRssFeedUri.Text.Trim() == ""); };
            txtAnaFeedUri.TextChanged += delegate(object sender, EventArgs e)
            { this.IsModified = true; btnValidateAna.Enabled = !(txtAnaFeedUri.Text == null || txtAnaFeedUri.Text.Trim() == ""); };
            numListRefreshTimeSpan.ValueChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            numYuluTimeSpan.ValueChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            chkAutoChangeYulu.CheckedChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            chkAutoRefreshList.CheckedChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };

            backgroundImageFolderTextBox.TextChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            chkUseBackImage.CheckedChanged += delegate(object sender, EventArgs e)
            {
                backgroundImageFolderTextBox.Enabled = chkUseBackImage.Checked;
                browseButton.Enabled = chkUseBackImage.Checked;
                this.IsModified = true;
            };


            radioYandui.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
            //radioRss.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
            radioYandui.Checked = true;

            numAnaFormWidth.ValueChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            numAnaFormHeight.ValueChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            cmbThemes.SelectedIndexChanged += delegate(object sender, EventArgs e)
            {
                if((cmbThemes.SelectedItem as string) != settings.AnaTheme)
                    this.IsModified = true;
            };

            numScreenSaver_AnaWidth.ValueChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            numScreenSaver_AnaHeight.ValueChanged += delegate(object sender, EventArgs e) { this.IsModified = true; };
            cmbScreenSaver_Themes.SelectedIndexChanged += delegate(object sender, EventArgs e)
            {
                if ((cmbScreenSaver_Themes.SelectedItem as string) != settings.ScreenSaver_AnaTheme)
                    this.IsModified = true;
            };


            btnThemeManager.Click += new EventHandler(btnThemeManager_Click);
            btnThemeManager2.Click +=new EventHandler(btnThemeManager_Click);
        }

        /// <summary>
        /// 使用 主题列表 填充 cmbThemes 。
        /// </summary>
        void FillCmdThemes()
        {
            string theme = cmbThemes.SelectedItem as string;
            string scr_theme = cmbScreenSaver_Themes.SelectedItem as string;

            cmbThemes.Items.Clear();
            cmbScreenSaver_Themes.Items.Clear();
            foreach (string themeName in ThemeHelper.Default.SupportThemeNames)
            {
                cmbThemes.Items.Add(themeName);
                cmbScreenSaver_Themes.Items.Add(themeName);
            }
            //尝试重新选中原来的选中项
            cmbThemes.SelectedItem = theme;
            cmbScreenSaver_Themes.SelectedItem = scr_theme;
        }
        void btnThemeManager_Click(object sender, EventArgs e)
        {
            ThemeManagerForm form = new ThemeManagerForm();
            form.ShowDialog(this.TopLevelControl);

            FillCmdThemes();
        }


        protected override void OnLoad(EventArgs e)
        {
            LoadSettings();
            base.OnLoad(e);
        }

        private void LoadSettings()
        {
            chkAutoStart.Checked = AutoStartHelper.IsValueExist();

            chkHideMainForm.Checked = settings.HideMainFormWhenStart;

            if (settings.UseRss)
                radioRss.Checked = true;
            else
                radioYandui.Checked = true;

            backgroundImageFolderTextBox.Text = settings.BackgroundImagePath;
            chkUseBackImage.Checked = settings.ScreenSaver_UseImageBack;
            txtRssFeedUri.Text = settings.RssFeedUri;
            txtAnaFeedUri.Text = settings.AnaFeedUri;

            numListRefreshTimeSpan.Value = settings.FreshDataInterval;
            numYuluTimeSpan.Value = settings.ChangeArticleInterval;
            chkAutoChangeYulu.Checked = settings.AutoChangeArticle;
            chkAutoRefreshList.Checked = settings.AutoFreshData;

            cmbYanduiType.SelectedItem = settings.AnaCollection;

            cmbThemes.SelectedItem = settings.AnaTheme;
            numAnaFormWidth.Value = settings.AnaSize.Width;
            numAnaFormHeight.Value = settings.AnaSize.Height;

            cmbScreenSaver_Themes.SelectedItem = settings.ScreenSaver_AnaTheme;
            numScreenSaver_AnaWidth.Value = settings.ScreenSaver_AnaSize.Width;
            numScreenSaver_AnaHeight.Value = settings.ScreenSaver_AnaSize.Height;

            this.IsModified = false;
        }
        // 应用自上次按下“应用”按钮后发生的所有更改
        private void ApplyChanges()
        {
            AutoStartHelper.AutoStartSwitch(chkAutoStart.Checked);

            settings.HideMainFormWhenStart = chkHideMainForm.Checked;

            settings.UseRss = radioRss.Checked;
            settings.BackgroundImagePath = backgroundImageFolderTextBox.Text;
            settings.ScreenSaver_UseImageBack = chkUseBackImage.Checked;
            settings.RssFeedUri = txtRssFeedUri.Text;
            settings.AnaFeedUri = txtAnaFeedUri.Text;

            settings.FreshDataInterval = (int)numListRefreshTimeSpan.Value;
            settings.ChangeArticleInterval = (int)numYuluTimeSpan.Value;
            settings.AutoChangeArticle = chkAutoChangeYulu.Checked;
            settings.AutoFreshData = chkAutoRefreshList.Checked;

            settings.AnaCollection = cmbYanduiType.SelectedItem as string;

            settings.AnaTheme = cmbThemes.SelectedItem as string;
            settings.AnaSize = new Size((int)numAnaFormWidth.Value,(int)numAnaFormHeight.Value);

            settings.ScreenSaver_AnaTheme = cmbScreenSaver_Themes.SelectedItem as string;
            settings.ScreenSaver_AnaSize = new Size((int)numScreenSaver_AnaWidth.Value, (int)numScreenSaver_AnaHeight.Value);

            settings.Save();
            this.IsModified = false;
        }


        void RadioButton_CheckedChanged(object sender, EventArgs e)
        {
            panelRss.Enabled = radioRss.Checked;
            panelYandui.Enabled = radioYandui.Checked;

            this.IsModified = true;
        }

        bool isModified = false;
        public bool IsModified
        {
            get { return isModified; }
            set
            {
                if (isModified == value)
                    return;

                isModified = value;

                btnApply.Enabled = isModified;
                btnReset.Enabled = isModified;
            }

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                ApplyChanges();
            }
            catch (ConfigurationException)
            {
                MessageBox.Show("无法保存您的设置。请确保程序所在的目录包含一个 .config 文件", "未能保存设置", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            ApplyChanges();
            btnApply.Enabled = false;
        }

        // 检查用户提供的 URI 是否指向一个有效的 RSS 源
        private void validateButton_Click(object sender, EventArgs e)
        {
            if(RssSource.Validate(txtRssFeedUri.Text))
                MessageBox.Show(this.TopLevelControl, "这是一个有效的 RSS 源。", "数据源有效", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
                MessageBox.Show(this.TopLevelControl, "不是一个有效的 RSS 源。可能是网络访问失败，或目标格式不正确。", "数据源无效", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            // 打开一个“打开文件”对话框，以选择一幅图像
            backgroundImageFolderBrowser.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            DialogResult result = backgroundImageFolderBrowser.ShowDialog();
            if (result == DialogResult.OK)
            {
                backgroundImageFolderTextBox.Text = backgroundImageFolderBrowser.SelectedPath;

                this.IsModified = true;
            }
        }

        private void linkYandui_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {//访问网站
            try
            {
                System.Diagnostics.Process.Start(linkYandui.Text);
            }
            catch
            {
                //无法打开网站。
            }
        }

        private void btnValidateAna_Click(object sender, EventArgs e)
        {
            string anaUrl = txtAnaFeedUri.Text;

            //if (anaUrl == null || anaUrl.Trim() == "")
            //{//如果为空，则使用默认的集合
            //    string key = cmbYanduiType.SelectedItem as string;
            //    anaUrl = Yandui.GetAnaUrl(key);
            //}

            if (AnaSource.Validate(anaUrl))
                MessageBox.Show(this.TopLevelControl,"这是一个有效的言兑语录源。", "数据源有效", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
                MessageBox.Show(this.TopLevelControl, "不是一个有效的言兑语录源。可能是网络访问失败，或目标格式不正确。", "语录源无效", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(this.TopLevelControl,"重置操作将使你之前的修改丢失，继续吗？","确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                LoadSettings();
            }
        }
    }
}